package com.itheima.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Override
    public void deductBalanceById(Long id, Integer amount) {
        //1.查询用户
        User user = this.getById(id);
        //2.判断状态
        if (user == null || UserStatus.FREEZE == user.getStatus()){
            throw new RuntimeException("用户不存在或已禁用");
        }
        //3.判断余额
        if (user.getBalance() < amount){
            throw new RuntimeException("余额不足");
        }
        //4.扣减库存
//        baseMapper.deductBalanceById(id, amount);
        int remainBalance = user.getBalance() - amount;
        this.lambdaUpdate()
                .set(User::getBalance, remainBalance)
                .set(remainBalance == 0, User::getStatus, 2)
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance())
                .update();
    }

    @Override
    public UserVO queryUserAddressById(Long id) {
        //查询用户
        User user = getById(id);
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        //根据用户id查询用户的收货地址列表
        List<Address> addressList = Db.lambdaQuery(Address.class)
                .eq(Address::getUserId, id)
                .list();
        userVO.setAddresses(BeanUtil.copyToList(addressList, AddressVO.class));
        return userVO;

    }
    @Override
    public List<UserVO> queryUserAndAddressByIds(List<Long> ids){
        //1.找出用户列表
        List<User> userList = this.listByIds(ids);
        List<UserVO> userVOS = BeanUtil.copyToList(userList, UserVO.class);
        //2.根据用户id集合查询出用户的收货地址列表，并转换为map，用户id为key，地址列表为value
        List<Address> addressList = Db.lambdaQuery(Address.class)
                .in(Address::getUserId, ids)
                .list();
        Map<Long, List<AddressVO>> addressVoMap = BeanUtil.copyToList(addressList, AddressVO.class)
                .stream().collect(Collectors.groupingBy(AddressVO::getUserId));
        //3.回填用户列表的收货地址列表
        for (UserVO userVO : userVOS) {
            userVO.setAddresses(addressVoMap.get(userVO.getId()));
        }
        return userVOS;
    }
}
